<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input :placeholder="'姓名'" v-model="listQuery.name" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-select v-model="listQuery.wait_status3" :placeholder="'待面试状态'" clearable style="width: 120px" class="filter-item">
        <el-option :label="'未联系'" :value="0"/>
        <el-option :label="'已联系未安排'" :value="2"/>
        <el-option :label="'无法联系'" :value="3"/>
      </el-select>
      <el-select v-model="listQuery.sex" :placeholder="'性别'" clearable style="width: 140px" class="filter-item">
        <el-option :label="'男'" :value="0"/>
        <el-option :label="'女'" :value="1"/>
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
      <el-button class="filter-item" icon="el-icon-download" type="success" @click="exportExcel">导出</el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange">
      <!--<el-table-column :label="'序号'" prop="id" align="center" width="65">-->
      <!--<template slot-scope="scope">-->
      <!--<span>{{ scope.row.id }}</span>-->
      <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column :label="'姓名'" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'性别'" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.sex_name }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'出生日期'" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.birthday }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'学历'" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.education }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'学校'" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.university }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'专业'" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.profession }}</span>
        </template>
      </el-table-column>
      <el-table-column label="推荐岗位" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.recommend }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'招聘状态'" class-name="status-col" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.interview_status_name }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'待面试状态'" class-name="status-col" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.wait_status3_name }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'完整简历'" class-name="status-col" align="center">
        <template slot-scope="scope">
          <a v-if="scope.row.resume" :href="scope.row.resume" target="_blank"><el-button type="text">预览简历</el-button></a>
          <el-button v-else type="text" disabled>无简历</el-button>
        </template>
      </el-table-column>
      <el-table-column :label="'面试安排'" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-select v-model="scope.row.wait_status3" placeholder="请选择" @change="do_action(scope.row)">
            <el-option :label="'未联系'" :value="0"></el-option>
            <el-option :label="'已联系未安排'" :value="2"></el-option>
            <el-option :label="'无法联系'" :value="3"></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column :label="'操作'" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="success" size="small" @click="readyHr(scope.row)">HR终面</el-button>
          <el-button type="danger" size="small" @click="handleBackPool(scope.row)">存入人才库</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" layout="total, prev, pager, next" @pagination="getList" />

    <el-dialog :title="'新建项目'" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="90px" style="width: 400px; margin-left:50px;">
        <el-form-item :label="'项目名称：'">
          <el-input v-model="temp.title" placeholder="给项目起个名字"/>
        </el-form-item>
        <el-form-item :label="'选择日期：'">
          <el-date-picker
            v-model="temp.timestamp"
            :picker-options="pickerOptions"
            class="filter-item"
            style="width: 400px;line-height: 30px"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item :label="'参与部门：'">
          <el-select v-model="temp.status" class="filter-item" placeholder="Please select">
            <el-option v-for="item in statusOptions" :key="item" :label="item" :value="item"/>
          </el-select>
        </el-form-item>
        <el-form-item :label="'招聘岗位：'">
          <el-select v-model="temp.status" class="filter-item" placeholder="Please select">
            <el-option v-for="item in statusOptions" :key="item" :label="item" :value="item"/>
          </el-select>
        </el-form-item>
        <el-form-item :label="'负责人：'">
          <el-select v-model="temp.status" class="filter-item" placeholder="Please select">
            <el-option v-for="item in statusOptions" :key="item" :label="item" :value="item"/>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel"/>
        <el-table-column prop="pv" label="Pv"/>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>

    <el-dialog :visible.sync="hrDialogVisible" width="30%" title="HR终面-面试批次">
      <el-form ref="hrForm" :rules="hrFormRules" :model="hrForm" label-width="80px">
        <el-form-item label="面试批次" prop="time">
          <el-date-picker v-model="hrForm.time" :picker-options="pickerOptions2" type="date" placeholder="请选择面试时间" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="面试组别" prop="group">
          <el-select v-model="hrForm.group" clearable placeholder="请选择组别">
            <el-option label="A" value="A"></el-option>
            <el-option label="B" value="B"></el-option>
            <el-option label="C" value="C"></el-option>
            <el-option label="D" value="D"></el-option>
            <el-option label="E" value="E"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="hrDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="hrCreateData">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { fetchPv, createArticle, updateArticle } from '@/api/article'
import { getWaitingHrList, updateWaiting, backTalentPool } from '@/api/interview'
import { exportWaitingHrList } from '@/api/export'
import { sendHr } from '@/api/talent'
import waves from '@/directive/waves' // Waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj ,such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'WaitingHr',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: undefined,
        wait_status3: undefined,
        sex: undefined
      },
      hrDialogVisible: false,
      queryString: '',
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        type: '',
        status: 'published'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      hrFormRules: {
        time: [
          { required: true, message: '请选择面试时间', trigger: 'change' }
        ],
        group: [
          { required: true, message: '请选择面试组别', trigger: 'change' }
        ]
      },
      downloadLoading: false,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      pickerOptions2: {
        disabledDate(value) {
          if (Date.now() >= value) {
            return true
          }
          return false
        }
      },
      job_id: undefined,
      hrForm: {
        id: undefined,
        time: undefined,
        group: undefined
      }
    }
  },
  created() {
    const param = this.$route.query
    if (param && param.action === 'quick') {
      this.job_id = param.id
    }
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getWaitingHrList(this.listQuery.page, this.queryString).then(response => {
        this.list = response.data.data
        this.total = response.data.meta.pagination.total
        this.listQuery.page = response.data.meta.pagination.current_page++
      }).catch(err => {
        console.log(err)
      }).finally(() => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      let query = ''
      const name = this.listQuery.name
      const wait_status3 = this.listQuery.wait_status3
      const sex = this.listQuery.sex
      if (name) {
        query += `name=${name}&`
      }
      if (wait_status3 || wait_status3 === 0 || wait_status3 === '0') {
        query += `wait_status3=${wait_status3}&`
      }
      if (sex || sex === 0 || sex === '0') {
        query += `sex=${sex}&`
      }
      this.queryString = query
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          this.temp.author = 'vue-element-admin'
          createArticle(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateArticle(tempData).then(() => {
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.temp)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    handleBackPool(row) {
      backTalentPool(row.id).then(response => {
        this.$notify({
          title: '成功',
          message: '操作成功',
          type: 'success',
          duration: 2000
        })
        const index = this.list.indexOf(row)
        this.list.splice(index, 1)
      }).catch(err => {
        console.log(err)
      })
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    readyHr(data) {
      this.hrDialogVisible = true
      this.hrForm.id = data.id
      this.$nextTick(() => {
        this.$refs['hrForm'].clearValidate()
      })
    },
    hrCreateData() {
      this.$refs['hrForm'].validate(valid => {
        if (valid) {
          const id = this.hrForm.id
          const time = this.hrForm.time
          const group = this.hrForm.group
          sendHr(id, time, group).then(response => {
            this.hrDialogVisible = false
            this.getList()
            this.$message({
              message: '操作成功',
              type: 'success'
            })
          }).catch(err => {
            console.log(err)
          })
        }
      })
    },
    do_action(row) {
      const id = row.id
      const data = { wait_status: row.wait_status3, step: 'hr' }
      updateWaiting(id, data).then(response => {
        for (const v of this.list) {
          if (v.id === response.data.id) {
            const index = this.list.indexOf(v)
            this.list.splice(index, 1, response.data)
            break
          }
        }
        this.$message({
          message: '操作成功',
          type: 'success'
        })
      })
    },
    exportExcel() {
      exportWaitingHrList(this.listQuery).then(response => {
        window.location.href = response.data.url
      })
    }
  }
}
</script>
